import time

import requests
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
import flaskConfig

app = Flask(__name__)
app.config.from_object(flaskConfig)
db = SQLAlchemy(app)


@app.route('/query_all', methods=['GET', 'POST'])
def query_all():
	from model import data_table
	persons = data_table.query.all()
	res = []
	for i in range(0, len(persons)):
		res.append(persons[i].to_dict())
	return jsonify({'h_code': 1, 'total': len(persons), 'pageSize': len(persons), 'res': res})


@app.route('/query', methods=['POST'])
def query():
	from model import data_table
	try:
		receive = request.get_json()
		persons = data_table.query.order_by(data_table.id.desc()).paginate(page=receive['page'],
		                                                                   per_page=receive['pageSize'],
		                                                                   error_out=False)
		res = []
		for i in range(0, len(persons.items)):
			# print(persons[i].to_dict())
			res.append(persons.items[i].to_dict())
		return jsonify({'h_code': 1, 'total': persons.total, 'pageSize': receive['pageSize'], 'res': res})
	except:
		return jsonify({'h_code': -1, 'msg': "query ERROR!"})


@app.route('/add', methods=['POST'])
def add():
	time_now = int(round(time.time() * 1000))
	from model import data_table
	detail = request.get_json()
	new_person = data_table()
	new_person.id = 0
	new_person.name = detail['name']
	new_person.hash_code = detail['hash_code']
	new_person.positive = detail['positive']
	new_person.date = str(time_now)
	try:
		db.session.add(new_person)
		db.session.commit()
		return jsonify({'h_code': 1, 'msg': detail})
	except:
		db.session.rollback()
		return jsonify({'h_code': -1, 'msg': "add ERROR!"})


@app.route('/delete', methods=['POST'])
def delete():
	from model import data_table, db
	detail = request.get_json()
	try:
		for id in detail['ids']:
			row = data_table.query.filter_by(id=id).first()
			db.session.delete(row)
			db.session.commit()
		return jsonify({'h_code': 1, 'msg': detail})
	except:
		db.session.rollback()
		return jsonify({'h_code': -1, 'msg': "delete ERROR!"})


@app.route('/modify', methods=['POST'])
def modify():
	from model import data_table
	detail = request.get_json()
	try:
		new_peoson = data_table.query.filter_by(id=detail['id']).first()
		new_peoson.name = detail['name']
		new_peoson.hash_code = detail['hash_code']
		new_peoson.positive = detail['positive']
		new_peoson.date = detail['date']
		db.session.commit()
		return jsonify({'h_code': 1, 'msg': detail})
	except:
		db.session.rollback()
		return jsonify({'h_code': -1, 'msg': "modify ERROR!"})


@app.route('/broadcast', methods=['POST'])
def broadcast():
	try:
		receive = request.get_json()
		detail = requests.post("http://xerxeslee.top:16001/backend", json=receive).json()
		return jsonify({'h_code': 1, 'msg': detail})
	except:
		return jsonify({'h_code': -1, 'msg': "broadcast ERROR!"})


@app.route('/add_broadcast_record', methods=['POST'])
def add_broadcast_record():
	from model import broadcast_history
	time_now = int(round(time.time() * 1000))
	try:
		receive = request.get_json()
		records = []
		for i in range(0, len(receive)):
			# print(receive[i])
			record = broadcast_history()
			record.id = 0
			record.name = receive[i]['name']
			record.hash_code = receive[i]['hash_code']
			record.positive = receive[i]['positive']
			record.date = receive[i]['date']
			record.broadcast_date = str(time_now)
			records.append(record)
		db.session.add_all(records)
		db.session.commit()
		return jsonify({'h_code': 1, 'msg': receive})
	except:
		return jsonify({'h_code': -1, 'msg': "add_broadcast_record ERROR!"})


@app.route('/query_history', methods=['POST'])
def query_history():
	from model import broadcast_history
	try:
		receive = request.get_json()
		persons = broadcast_history.query.order_by(broadcast_history.id.desc()).paginate(page=receive['page'],
		                                                                                 per_page=receive['pageSize'],
		                                                                                 error_out=False)
		res = []
		for i in range(0, len(persons.items)):
			res.append(persons.items[i].to_dict())
		return jsonify({'h_code': 1, 'total': persons.total, 'pageSize': receive['pageSize'], 'res': res})
	except:
		return jsonify({'h_code': -1, 'msg': "query_history ERROR!"})


@app.route('/delete_history', methods=['POST'])
def delete_history():
	from model import broadcast_history, db
	detail = request.get_json()
	try:
		row = broadcast_history.query.filter_by(id=detail['id']).first()
		db.session.delete(row)
		db.session.commit()
		return jsonify({'h_code': 1, 'msg': detail})
	except:
		db.session.rollback()
		return jsonify({'h_code': -1, 'msg': "delete_history ERROR!"})


if __name__ == '__main__':
	app.run(host="0.0.0.0", port=13001)
